package com.sfjswl.fp.core.relation;

import com.sfjswl.fp.common.enums.NodeRunStateEnum;
import com.sfjswl.fp.core.base.BaseNode;
import com.sfjswl.fp.core.base.BaseRelation;
import com.sfjswl.fp.core.context.RuleContext;
import com.sfjswl.fp.core.utils.RuleLinkedList;

public final class And extends BaseRelation {

    @Override
    protected NodeRunStateEnum processNode(RuleContext ctx) {
        RuleLinkedList<BaseNode> children = this.getChildren();
        if (children == null || children.isEmpty()) {
            return NodeRunStateEnum.NONE;
        }
        boolean hasTrue = false;
        for (RuleLinkedList.Node<BaseNode> listNode = children.getLeft(); listNode != null; listNode = listNode.next) {
            BaseNode node = listNode.item;
            if (node != null) {
                NodeRunStateEnum stateEnum = node.process(ctx);
                if (stateEnum == NodeRunStateEnum.FALSE) {
                    return NodeRunStateEnum.FALSE;
                }
                if (!hasTrue) {
                    hasTrue = stateEnum == NodeRunStateEnum.TRUE;
                }
            }
        }

        if (hasTrue) {
            return NodeRunStateEnum.TRUE;
        }
        return NodeRunStateEnum.NONE;
    }
}
